package pl.lodz.p.browarex.dao;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Repository;

import pl.lodz.p.browarex.base.BaseCrudDao;
import pl.lodz.p.browarex.model.User;

@Repository
public class UserDAO extends BaseCrudDao<User, Long> {

	public UserDAO(Class<User> type) {
		super(type);
	}

	public UserDAO() {
		super(User.class);
	}

	public User getByUsername(String username) {
		Criteria criteria = getSession().createCriteria(type);
		criteria.add(Restrictions.eq("username", username));
		return (User) criteria.uniqueResult();
	}

	public User getLogged() {

		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();

		if (principal instanceof UserDetails) {
			return getByUsername(((UserDetails) principal).getUsername());
		}
		return null;
	}

}
